/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
 *
 */

import { ProjectBuildOption, TestCaseFun } from "../../plugins/task-builder/test-case";
import {
  AbilityType,
  APIType,
  APIVersion,
  LanguageType, ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from "../../plugins/project-builder/models/constants";
import path from "path";
import fse from "fs-extra";
import { addOhPackageDps, commonJson5Operation } from "../../plugins/common-fun";
import { initExecuteCommand, runHvigorAsync } from "../../common/common";
import { expect } from "@jest/globals";
import { TestCaseBuilder } from "../../plugins/task-builder/task-case-builder";
import { TestTaskOptionBuilder } from "../../plugins/task-builder/test-task-option";
import { WorkerDataEts, WorkerDataTs } from "../../plugins/common-data";

const testCaseDescription = 'hsp依赖native-hsp模块构建worker';

// 1、创建stage工程
const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  // 2、新增Shared Library和Shared Library1
  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 2
  }
}

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const hspPath = project.getModule('shareLibrary').moduleRootPath();
  const hsp1Path = project.getModule('shareLibrary1').moduleRootPath();

  // 3、Shared Library和Native-Shared Library1模块下新增Worker.ets
  const workerData = project.option.apiType === APIType.STAGE ? WorkerDataEts : WorkerDataTs;
  const extendStr = project.option.apiType === APIType.STAGE ? 'ets' : 'ts';

  await fse.ensureDir(path.resolve(hspPath, 'src/main/ets/workers'));
  await fse.writeFile(path.resolve(hspPath, `src/main/ets/workers/Worker.${extendStr}`), workerData);
  await fse.ensureDir(path.resolve(hsp1Path, 'src/main/ets/workers'));
  await fse.writeFile(path.resolve(hsp1Path, `src/main/ets/workers/Worker.${extendStr}`), workerData);
  const hspWorkerEtsPath = path.resolve(hspPath, `src/main/ets/workers/Worker.${extendStr}`);

  await commonJson5Operation(path.resolve(hspPath, 'build-profile.json5'), async (json5: any) => {
    json5.buildOption.sourceOption = {
      'workers': [
        `./src/main/ets/workers/Worker.${extendStr}`,
      ]
    };
  });
  await commonJson5Operation(path.resolve(hsp1Path, 'build-profile.json5'), async (json5: any) => {
    json5.buildOption.sourceOption = {
      'workers': [
        `./src/main/ets/workers/Worker.${extendStr}`,
      ]
    };
  });

  // 4、Shared Library模块依赖Native-Shared Library1模块
  await addOhPackageDps(hspPath, {'@ohos/shareLibrary1': 'file:../shareLibrary1'});

  // 5、菜单栏Make Module 'library'
  const makeModuleHspCommands = initExecuteCommand({
    mode: 'module',
    module: 'shareLibrary',
    product: 'default',
    tasks: 'assembleHsp'
  });

  const makeModuleHspResult = await runHvigorAsync(projectRootPath, makeModuleHspCommands);
  expect(makeModuleHspResult.stdout).toContain('BUILD SUCCESSFUL');

  // 路径hsp-build-default-intermediates-loader-default-loader.json文件中有hsp和har的Worker.ets路径
  const hspBuildLoaderJsonPath = path.resolve(hspPath, 'build/default/intermediates/loader/default/loader.json');
  // 路径hsp-build-default-cache-default-default@CompileArkTS-esmodule-debug-filesInfo.txt路径
  const hspBuildFileInfoTxtPath = path.resolve(hspPath, 'build/default/cache/default/default@CompileArkTS/esmodule/debug/filesInfo.txt');

  const hspBuildLoaderJsonStr = fse.readFileSync(hspBuildLoaderJsonPath).toString();
  const hspBuildFileInfoTxtStr = fse.readFileSync(hspBuildFileInfoTxtPath).toString();
  const hspWorkerEtsPathStr = hspWorkerEtsPath.replace(/\\/g, "\\\\");

  expect(hspBuildLoaderJsonStr.includes(hspWorkerEtsPathStr)).toBe(true);
  expect(hspBuildFileInfoTxtStr.includes("shareLibrary/src/main/ets/workers/Worker.ts")).toBe(true);
}

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_HSP_BUILD_WORKER_010')
  .description(testCaseDescription)
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.defaultOpt())
  .testFun(testFun)
  .load();